package cn.iocoder.yudao.module.trade.controller.admin.storeusers;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.trade.controller.admin.storeusers.vo.StoreUserUpdateStatusReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.storeusers.vo.StoreUsersPageReqVO;
import cn.iocoder.yudao.module.trade.controller.admin.storeusers.vo.StoreUsersRespVO;
import cn.iocoder.yudao.module.trade.controller.admin.storeusers.vo.StoreUsersSaveReqVO;
import cn.iocoder.yudao.module.trade.dal.dataobject.delivery.DeliveryPickUpStoreDO;
import cn.iocoder.yudao.module.trade.dal.dataobject.storeusers.StoreUsersDO;
import cn.iocoder.yudao.module.trade.service.delivery.DeliveryPickUpStoreService;
import cn.iocoder.yudao.module.trade.service.storeusers.StoreUsersService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Tag(name = "管理后台 - 店铺账号")
@RestController
@RequestMapping("/trade/store-users")
@Validated
public class StoreUsersController {

    @Resource
    private StoreUsersService storeUsersService;
    @Resource
    private DeliveryPickUpStoreService deliveryPickUpStoreService;

    @PostMapping("/create")
    @Operation(summary = "创建店铺账号")
//    @PreAuthorize("@ss.hasPermission('trade:store-users:create')")
    public CommonResult<Long> createStoreUsers(@Valid @RequestBody StoreUsersSaveReqVO createReqVO) {
        return success(storeUsersService.createStoreUsers(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新店铺账号")
//    @PreAuthorize("@ss.hasPermission('trade:store-users:update')")
    public CommonResult<Boolean> updateStoreUsers(@Valid @RequestBody StoreUsersSaveReqVO updateReqVO) {
        storeUsersService.updateStoreUsers(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除店铺账号")
    @Parameter(name = "id", description = "编号", required = true)
//    @PreAuthorize("@ss.hasPermission('trade:store-users:delete')")
    public CommonResult<Boolean> deleteStoreUsers(@RequestParam("id") Long id) {
        storeUsersService.deleteStoreUsers(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得店铺账号")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
//    @PreAuthorize("@ss.hasPermission('trade:store-users:query')")
    public CommonResult<StoreUsersRespVO> getStoreUsers(@RequestParam("id") Long id) {
        StoreUsersDO storeUsers = storeUsersService.getStoreUsers(id);
        return success(BeanUtils.toBean(storeUsers, StoreUsersRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得店铺账号分页")
//    @PreAuthorize("@ss.hasPermission('trade:store-users:query')")
    public CommonResult<PageResult<StoreUsersRespVO>> getStoreUsersPage(@Valid StoreUsersPageReqVO pageReqVO) {
        PageResult<StoreUsersDO> pageResult = storeUsersService.getStoreUsersPage(pageReqVO);
        PageResult<StoreUsersRespVO> result = BeanUtils.toBean(pageResult, StoreUsersRespVO.class);
        if (CollectionUtils.isNotEmpty(result.getList())) {
            Set<Long> storeIds = result.getList().stream().map(StoreUsersRespVO::getStoreId).collect(Collectors.toSet());
            List<DeliveryPickUpStoreDO> deliveryPickUpStoreList = deliveryPickUpStoreService.getDeliveryPickUpStoreList(storeIds);
            result.getList().forEach(e ->
                    deliveryPickUpStoreList.forEach(s -> {
                        if (Objects.equals(e.getStoreId(), s.getId())) {
                            e.setStoreName(s.getName());
                        }
                    })
            );
        }
        return success(result);
    }

    @PutMapping("/update-password")
    @Operation(summary = "重置用户密码")
//    @PreAuthorize("@ss.hasPermission('trade:store-users:update-password')")
    public CommonResult<Boolean> updateUserPassword(@RequestParam("id") Long id) {
        storeUsersService.updateUserPassword(id);
        return success(true);
    }

    @PutMapping("/update-status")
    @Operation(summary = "修改用户状态")
//    @PreAuthorize("@ss.hasPermission('trade:store-users:update')")
    public CommonResult<Boolean> updateUserStatus(@Valid @RequestBody StoreUserUpdateStatusReqVO reqVO) {
        storeUsersService.updateUserStatus(reqVO.getId(), reqVO.getStatus());
        return success(true);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出店铺账号 Excel")
//    @PreAuthorize("@ss.hasPermission('trade:store-users:export')")
    @OperateLog(type = EXPORT)
    public void exportStoreUsersExcel(@Valid StoreUsersPageReqVO pageReqVO,
                                      HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<StoreUsersDO> list = storeUsersService.getStoreUsersPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "店铺账号.xls", "数据", StoreUsersRespVO.class,
                BeanUtils.toBean(list, StoreUsersRespVO.class));
    }

}